const { Controller } = require('egg')
const fs = require('fs')
const axios = require('axios')

class DoriController extends Controller {
    static TABLE_MP_LOG = 'dori_mp_log'
    static TABLE_USER = 'dori_user'
    static REDIS_KEY_ACCESS_TOKEN = 'dori_mp_access_token'
    static TABLE_CATEGORY = 'dori_category'

    async mpLog({type, value}) {
        return await this.app.mysql.insert(DoriController.TABLE_MP_LOG, {
            type,
            value,
            create_time: new Date().getTime(),
            ip: this.ctx.state.clientIp,
        })
    }
    async wxLogin() {
        const { jscode } = this.ctx.query
        const { appid, secret } = this.app.config.dori_mp
        const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${jscode}&grant_type=authorization_code`
        const requestRes = await axios.get(url)

        // console.log('requestRes', requestRes.data)
        const { openid } = requestRes.data
        
        const getUser = await this.app.mysql.get('dori_user', {
            openid
        })

        let insertUser = null
        let updateUser = null
        if (!getUser) {
            insertUser = await this.app.mysql.insert('dori_user', {
                openid,
                create_time: new Date().getTime(),
                last_login_time: new Date().getTime()
            })
        } else {
            updateUser = await this.app.mysql.update('dori_user', {
                last_login_time: new Date().getTime()
            }, {
                where: {id: getUser.id}
            })
        }

        this.mpLog({ type: 'login', value: JSON.stringify({openid}) })
        this.ctx.body = {
            code: 200,
            msg: 'ok',
            data: {
                getUser,
                insertUser,
                updateUser,
                openid
            }
        }
    }

    async getUserInfo() {
        this.ctx.body = {
            code: 200,
            msg: 'ok',
            data: {
                ...this.ctx.currentUser
            }
        }
    }

    async getCategorys() {
        const res = await this.app.mysql.select(DoriController.TABLE_CATEGORY)
        
        this.ctx.body = {
            code: 200,
            msg: 'ok',
            data: [
                res.filter(v => v.type === 'in'),
                res.filter(v => v.type === 'out'),
            ]
        }
    }
}

module.exports = DoriController
